<template>
    <div ref="containerRef"></div>
</template>
<script setup lang="ts">
import { ref, onMounted, toRefs, computed, onUnmounted, watch } from "vue";
import { addFieldsToMarksArr, getImageAdaptSize, loadImage } from "./utils";
import EssayEvaluator from "./EssayEvaluator";
import { cloneDeep, debounce } from "lodash";

const { windowWidth, windowHeight } = uni.getSystemInfoSync();

const props = defineProps<{
    data: EssayEvaluatorData[];
    config: EssayEvaluatorConfig;
}>();
const { data, config } = toRefs(props);
const {
    stageWidth = windowWidth,
    stageHeight = windowHeight,
    dir,
    score,
    flunked = false,
} = config.value;

const emits = defineEmits<{
    markClick: [string, BaseMarkInfo];
}>();

const essayInstance = ref<EssayEvaluator>();
const containerRef = ref<any>();
const isVertical = computed(() => dir === "vertical");
// 数据存储与处理相关
const essayImageList = ref<EssayImageAttrs[]>([]);
const wordList = ref<BaseMarkInfo[]>([]);
const sentencesList = ref<BaseMarkInfo[]>([]);
const paragraphList = ref<BaseMarkInfo[]>([]);
const correctionList = ref<BaseMarkInfo[]>([]);

onMounted(async () => {
    await handleEssayImages(); // 处理图片信息
    handleMarkData();
    const size = calculateGroupSize();
    // 初始化图层和组
    const groupConfig = {
        width: isVertical.value ? stageWidth : size,
        height: isVertical.value ? size : stageHeight,
    };
    const essay = new EssayEvaluator({
        dir,
        subject: "chinese",
        // subject: "english",
        onMarkClick,
    });
    // 初始化stage
    essay.initStage({
        container: containerRef.value,
        width: stageWidth,
        height: stageHeight,
    });
    essay.initLayer(groupConfig);
    essay.renderBgImages(essayImageList.value); // 渲染背景图
    essay.renderMask(); //渲染半透明遮罩
    essay.renderScore(score); // 渲染分数
    // 如果试卷及格
    if (!flunked) {
        if (wordList.value.length > 0) {
            essay.renderWords(wordList.value);
            essay.bindMarkEvent("word");
        }
        if (sentencesList.value.length > 0) {
            essay.renderSentences(sentencesList.value);
            essay.bindMarkEvent("sentence");
        }
    }

    essay.bindDragAndScaleEvent();
    essayInstance.value = essay;
});

watch(
    () => config.value.viewType,
    (newViewType, oldViewType) => {
        const essayIns = essayInstance.value;
        if (newViewType === "comprehensive") {
            if (oldViewType === "wordsentence") {
                essayIns?.clearOrderNumber("sentence");
                essayIns?.cancelMarkHighlight("word", "sentence");
            } else if (oldViewType === "paragraph") {
                essayIns?.unBindMarkEvent("paragraph");
                essayIns?.clearMark("paragraph");
                essayIns?.clearOrderNumber("paragraph");
                essayIns?.renderWords(wordList.value);
                essayIns?.renderSentences(sentencesList.value);
                essayIns?.bindMarkEvent("word", "sentence");
            }
        } else if (newViewType === "paragraph") {
            if (oldViewType === "wordsentence") {
                essayIns?.unBindMarkEvent("word", "sentence");
                essayIns?.cancelMarkHighlight("word", "sentence");
                essayIns?.clearOrderNumber("sentence");
            }
            essayIns?.clearMark("word", "sentence");
            if (paragraphList.value.length > 0) {
                essayIns?.renderParagraphs(paragraphList.value);
                essayIns?.renderOrderNumber("paragraph");
                essayIns?.bindMarkEvent("paragraph");
            }
        } else if (newViewType === "wordsentence") {
            if (oldViewType === "paragraph") {
                essayIns?.unBindMarkEvent("paragraph");
                essayIns?.clearMark("paragraph");
                essayIns?.clearOrderNumber("paragraph");
                essayIns?.renderWords(wordList.value);
                essayIns?.renderSentences(sentencesList.value);
            }
            essayIns?.renderOrderNumber("sentence");
        }
    }
);
watch(
    () => config.value.stageHeight,
    (newHeight) => {
        essayInstance.value?.adaptHeight(newHeight);
    }
);
watch(
    () => data.value,
    debounce((newValue, oldValue) => {
        handleMarkData();
    }, 300),
    { deep: true }
);
watch(
    () => wordList.value,
    (nl, ol) => {
        const viewType = config.value.viewType;
        if (nl.length > 0) {
            if (viewType !== "paragraph") {
                essayInstance.value?.renderWords(nl);
                essayInstance.value?.bindMarkEvent("word");
                console.log("essayInstance", essayInstance.value.mainGroup);
            }
        }
    }
);
watch(
    () => sentencesList.value,
    (nl, ol) => {
        const viewType = config.value.viewType;
        if (nl.length > 0) {
            if (viewType !== "paragraph") {
                essayInstance.value?.renderSentences(nl);
                essayInstance.value?.bindMarkEvent("sentence");
                if (viewType === "wordsentence") {
                    essayInstance.value?.renderOrderNumber("sentence");
                }
            }
        }
    }
);
watch(
    () => paragraphList.value,
    (nl, ol) => {
        const viewType = config.value.viewType;
        if (nl.length > 0) {
            if (viewType === "paragraph") {
                essayInstance.value?.renderParagraphs(nl);
                essayInstance.value?.renderOrderNumber("paragraph");
                essayInstance.value?.bindMarkEvent("paragraph");
            }
        }
    }
);
watch(
    () => correctionList.value,
    (nl, ol) => {
        if (nl.length > 0) {
            essayInstance.value?.renderCorrections(nl);
            essayInstance.value?.renderOrderNumber("correction");
            essayInstance.value?.bindMarkEvent("correction");
        }
    }
);

onUnmounted(() => {
    essayInstance.value?.unBindDragAndScaleEvent();
    essayInstance.value?.unBindMarkEvent("word", "sentence", "paragraph");
});

// 处理图片信息
const handleEssayImages = async () => {
    const urls = data.value.map((item) => item.url);
    const imgs = [];

    for (let i = 0; i < urls.length; i++) {
        const img = await loadImage(urls[i]);
        const { width, height } = await getImageAdaptSize(img, {
            dir,
            stageWidth,
            stageHeight,
        });
        const x = isVertical.value ? 0 : i === 0 ? 0 : imgs[i - 1].width;
        const y: number = isVertical.value
            ? i === 0
                ? 0
                : imgs[i - 1].height
            : 0;
        const adaptScale = isVertical.value
            ? stageWidth / img.width
            : stageHeight / img.height;

        data.value[i].adaptScale = adaptScale;
        imgs.push({
            img,
            x,
            y,
            width,
            height,
        });
    }
    essayImageList.value = imgs;
};
// 计算图片组尺寸
const calculateGroupSize = () => {
    let size = 0;
    for (let i = 0; i < essayImageList.value.length; i++) {
        const { width, height } = essayImageList.value[i];
        size += isVertical.value ? height : width;
    }
    return size;
};
// 处理 props 数据
const handleMarkData = () => {
    if (essayImageList.value.length === 0) return;

    let wordArr: BaseMarkInfo[] = [],
        sentencesArr: BaseMarkInfo[] = [],
        paragraphArr: BaseMarkInfo[] = [],
        correctionArr: BaseMarkInfo[] = [];

    for (let i = 0; i < data.value.length; i++) {
        const { selections, adaptScale } = data.value[i];
        // 此处改为深拷贝，防止多触发一次上面的watch
        const words = cloneDeep(selections.words || []);
        const sentences = cloneDeep(selections.sentences || []);
        const paragraphs = cloneDeep(selections.paragraphs || []);
        const corrections = cloneDeep(selections.corrections || []);
        // 添加额外信息到marks中
        addFieldsToMarksArr([words, sentences, paragraphs, corrections], {
            paperIndex: i, // 试卷索引
            isHighlight: false, // 是否高亮
        });
        // 处理坐标
        handleMarksCooridates(words, adaptScale as number);
        handleMarksCooridates(sentences, adaptScale as number);
        handleMarksCooridates(paragraphs, adaptScale as number);
        handleMarksCooridates(corrections, adaptScale as number);
        // 添加到列表中
        wordArr = [...wordArr, ...words];
        sentencesArr = [...sentencesArr, ...sentences];
        paragraphArr = [...paragraphArr, ...paragraphs];
        correctionArr = [...correctionArr, ...corrections];
    }

    wordList.value = wordArr;
    sentencesList.value = sentencesArr;
    paragraphList.value = paragraphArr;
    correctionList.value = correctionArr;
};
// 处理坐标
const handleMarksCooridates = (marks: BaseMarkInfo[], adaptScale: number) => {
    marks.forEach((mark: BaseMarkInfo) => {
        const { paperIndex } = mark;
        const cooridates = mark.cooridates;
        cooridates.forEach((cooridate: BaseShapeAttrs) => {
            const x1 = cooridate.x1 * adaptScale;
            const y1 = cooridate.y1 * adaptScale;
            const x2 = cooridate.x2 * adaptScale;
            const y2 = cooridate.y2 * adaptScale;
            const { x: imageX, y: imageY } =
                essayImageList.value[paperIndex as number];
            cooridate.x = isVertical.value ? x1 : x1 + imageX;
            cooridate.y = isVertical.value ? y1 + imageY : y1;
            cooridate.width = x2 - x1;
            cooridate.height = y2 - y1;
        });
    });
};
// const cancelMarkHighlight = (type: string) => {
//     essayInstance.value?.cancelMarkHighlight(type);
// };
const onMarkClick = (type: string, markInfo: BaseMarkInfo) => {
    emits(`markClick`, type, markInfo);
};
// defineExpose({
//     cancelMarkHighlight,
// });
</script>
